﻿using IOP.OpenType.Tables;
using IOP.OpenType;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace IOP.Codec.OpenType
{
    /// <summary>
    /// 横向度量头表加载器
    /// </summary>
    public class HheaTableLoader
    {
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="entry"></param>
        /// <returns></returns>
        public async Task<HheaTable> Load(FileStream stream, TableEntry entry)
        {
            uint offset = entry.Offset;
            uint length = entry.Length;
            stream.Seek(offset, SeekOrigin.Begin);
            Memory<byte> bytes = new byte[length];
            await stream.ReadAsync(bytes);
            var table = ReadHhea(bytes);
            table.Entry = entry;
            return table;
        }

        private HheaTable ReadHhea(Memory<byte> data)
        {
            ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>(data);
            SequenceReader<byte> reader = new SequenceReader<byte>(sequence);
            reader.TryReadBigEndian(out short majV);
            reader.TryReadBigEndian(out short minV);
            reader.TryReadBigEndian(out short ascender);
            reader.TryReadBigEndian(out short descender);
            reader.TryReadBigEndian(out short lineGap);
            reader.TryReadBigEndian(out short advanceWidthMax);
            reader.TryReadBigEndian(out short minLeftSideBearing);
            reader.TryReadBigEndian(out short minRightSideBearing);
            reader.TryReadBigEndian(out short xMaxExtent);
            reader.TryReadBigEndian(out short caretSlopeRise);
            reader.TryReadBigEndian(out short caretSlopeRun);
            reader.TryReadBigEndian(out short caretOffset);
            reader.Advance(sizeof(short) * 4);
            reader.TryReadBigEndian(out short metricDataFormat);
            reader.TryReadBigEndian(out short numberOfHMetrics);
            HheaTable table = new HheaTable
            {
                MajorVersion = (ushort)majV,
                MinorVersion = (ushort)minV,
                Ascender = ascender,
                Descender = descender,
                LineGap = lineGap,
                AdvanceWidthMax = (ushort)advanceWidthMax,
                MinLeftSideBearing = minLeftSideBearing,
                MinRightSideBearing = minRightSideBearing,
                XMaxExtent = xMaxExtent,
                CaretSlopeRise = caretSlopeRise,
                CaretSlopeRun = caretSlopeRun,
                CaretOffset = caretOffset,
                MetricDataFormat = metricDataFormat,
                NumberOfHMetrics = (ushort)numberOfHMetrics
            };
            return table;
        }
    }
}
